package com.rjwh.dingdong.client.activity.radio;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.AdapterView;
import android.widget.FrameLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;

import com.rjwh.dingdong.client.R;
import com.rjwh.dingdong.client.activity.BaseActivity;
import com.rjwh.dingdong.client.activity.player.fragment.PlayerToolbarFragment;
import com.rjwh.dingdong.client.adapter.RadioAlbumProgramListAdapter;
import com.rjwh.dingdong.client.bean.localbean.PlayList;
import com.rjwh.dingdong.client.bean.localbean.Song;
import com.rjwh.dingdong.client.mvp.presenter.impl.RadioLocalLocalPlayListPresenter;
import com.rjwh.dingdong.client.mvp.view.RadioLocalPlayListView;
import com.rjwh.dingdong.client.player.IPlayback;
import com.rjwh.dingdong.client.player.PlayConstants;
import com.rjwh.dingdong.client.player.PlayMode;
import com.rjwh.dingdong.client.player.PlayState;
import com.rjwh.dingdong.client.service.PlaybackService;
import com.rjwh.dingdong.client.util.LogUtil;
import com.rjwh.dingdong.client.util.RxBus;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import rx.Observable;
import rx.Subscriber;

import static com.baidu.location.d.j.v;

/**
 * @author Kay
 * @ClassName RadioLocalPlayListActivity
 * @Description
 * @date 2016-10-28
 * @history 2016-10-28 author: description:
 */
public class RadioLocalPlayListActivity extends BaseActivity implements RadioLocalPlayListView {
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.radio_local_play_list_lv)
    ListView radioPlayListLv;
    @BindView(R.id.radio_local_play_list_fm)
    FrameLayout radioLocalPlayListFm;
    @BindView(R.id.radio_local_play_list_empty_root_fl)
    RelativeLayout radioLocalPlayListEmptyRootFl;

    private RadioLocalLocalPlayListPresenter presenter;
    private Observable<Song> observableUpdateSong;
    private Observable<PlayState> observablePlayState;
    private IPlayback mPlayer;
    private RadioAlbumProgramListAdapter adapter;
    private PlayList playList = new PlayList();
    private int currentIndex = -1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.radio_local_play_lsit_layout);
        ButterKnife.bind(this);
        initObserver();
        initView();
        presenter = new RadioLocalLocalPlayListPresenter(this, this);
        presenter.subscribe();
    }

    public static void startActivity(Context context) {
        Intent intent = new Intent(context, RadioLocalPlayListActivity.class);
        context.startActivity(intent);
    }

    private void initObserver() {
        observableUpdateSong = RxBus.get().register(PlayConstants.ACTION_UPDATA_SONG, Song.class);
        observablePlayState = RxBus.get().register(PlayConstants.ACTION_PLAY_STATUS_CHANGED, PlayState.class);
        addSubscription(observableUpdateSong, subscriberUpdateSong);
        addSubscription(observablePlayState, subscriberPlayState);
    }

    private void initView() {
        initToolbarHelper();
        getSupportFragmentManager().beginTransaction().replace(R.id.radio_local_play_list_fm, PlayerToolbarFragment.getInstance()).commit();
        adapter = new RadioAlbumProgramListAdapter(this);
        radioPlayListLv.setAdapter(adapter);
        radioPlayListLv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//                if (mPlayer != null) {
//                    LogUtil.e("playList:" + playList.getSongs().size() + " position" + position);
//                    mPlayer.play(playList, position);
//                    currentIndex = position;
//                    updataListViewSelectState(position);
//                }
                if (mPlayer != null && playList != null) {
                    if (playList.getSongs().isEmpty()) {
                        //没有播放歌曲
                        LogUtil.d("playList:" + playList.getSongs().size() + " position" + position);
                        currentIndex = position;
                        mPlayer.play(playList, currentIndex);
                    } else {
                        //正在播放歌曲
                        if (currentIndex == position) {
                            //点击的是播放的条目
                            if (mPlayer.isPlaying()) {
                                mPlayer.pause();
                            } else {
                                mPlayer.play();
                            }
                        } else {
                            //点击的不是播放的条目
                            currentIndex = position;
                            mPlayer.play(playList, currentIndex);
                        }
                    }
                    LogUtil.e("RadioAlbumProgramActivi", "currentIndex:" + currentIndex);
                    updataListViewSelectState(currentIndex);
                }
            }
        });
    }

    private void initToolbarHelper() {
        this.setSupportActionBar(this.toolbar);
        if (getSupportActionBar() != null) {
            getSupportActionBar().setTitle(getResources().getString(R.string.radio_play_list));
        }
        getSupportActionBar().setHomeButtonEnabled(true); //设置返回键可用
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);
    }


    @Override
    public void onPlaybackServiceBound(PlaybackService service) {
        mPlayer = service;
    }

    @Override
    public void onPlaybackServiceUnbound() {
        mPlayer = null;
    }

    @Override
    public void onSongUpdated(@Nullable Song song) {
        //绑定服务成功以后去刷新列表中的状态
        if (adapter != null && !adapter.isEmpty()) {
            updataListViewSelectState(song);
        }
    }

    @Override
    public void updatePlayToggle(PlayState change) {
        adapter.setSelectIndex(change);
    }

    @Override
    public void updatePlayMode(PlayMode lastPlayMode) {

    }

    @Override
    public void updatePlayList(List<Song> songs) {

        if (songs != null && !songs.isEmpty()) {
            radioLocalPlayListEmptyRootFl.setVisibility(View.GONE);
            radioLocalPlayListFm.setVisibility(View.VISIBLE);
            //获取本地播放列表
            playList.setSongs(songs);
            adapter.clearAll();
            adapter.appendToList(songs);
            if (mPlayer != null) {
                updataListViewSelectState(mPlayer.getPlayingSong());
            }
        } else {
            radioLocalPlayListFm.setVisibility(View.GONE);
            radioLocalPlayListEmptyRootFl.setVisibility(View.VISIBLE);
        }
    }

    //刷新选中状态
    public void updataListViewSelectState(Song song) {
        //播放结束
        if (song == null) {
            currentIndex = -1;
            adapter.setSelectIndex(currentIndex, PlayState.STOP);
            return;
        }
        for (int i = 0, j = adapter.getList().size(); i < j; i++) {
            Song radioAlbumProgramData = adapter.getList().get(i);
            if (song.getProgramid().equals(radioAlbumProgramData.getProgramid())) {
                //自动播放
                currentIndex = i;
                if (mPlayer != null) adapter.setSelectIndex(i, mPlayer.getPlayStatus());
                break;
            }
        }
    }

    //刷新选中状态
    public void updataListViewSelectState(int index) {
        if (mPlayer != null) adapter.setSelectIndex(index, mPlayer.getPlayStatus());
    }

    //刷新播放的状态
    public void updataListViewItemPlayState(PlayState change) {
        if (currentIndex == -1) return;
        adapter.setSelectIndex(change);
    }

    Subscriber subscriberUpdateSong = new Subscriber<Song>() {
        @Override
        public void onCompleted() {

        }

        @Override
        public void onError(Throwable e) {

        }


        @Override
        public void onNext(Song song) {
            updataListViewSelectState(song);
        }
    };

    Subscriber subscriberPlayState = new Subscriber<PlayState>() {
        @Override
        public void onCompleted() {

        }

        @Override
        public void onError(Throwable e) {

        }


        @Override
        public void onNext(PlayState change) {
            updataListViewItemPlayState(change);
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        presenter.detachView();
        RxBus.get().unregister(PlayConstants.ACTION_UPDATA_SONG, observableUpdateSong);
        RxBus.get().unregister(PlayConstants.ACTION_PLAY_STATUS_CHANGED, observablePlayState);
    }
}
